/******************************************************************************\
    Thread.h contains a class of windows thread.
    Copyright (C) 2008  Victor Vinogradov (fly3333@gmail.com)

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
\******************************************************************************/

#ifndef __THREAD_HPP
#define __THREAD_HPP

#include ".\Handle.hpp"
#include <windows.h>
#include <process.h>

class cThread : public cObject< cSubHandle >
{
	unsigned long ThreadId;
public:
	bool Create( LPSECURITY_ATTRIBUTES lpThreadAttributes, SIZE_T dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter, DWORD dwCreationFlags )
	{
		unsigned long thread_id;
		long handle = ( long )_beginthreadex( ( void * )lpThreadAttributes, ( unsigned )dwStackSize, ( unsigned ( __stdcall * )( void * ) )lpStartAddress, ( void * )lpParameter, ( unsigned )dwCreationFlags, ( unsigned * )&thread_id );
		if( handle == -1L )
			return false;
		cSubHandle *sub_handle;
		try
		{
			sub_handle = new cSubHandle( ( HANDLE )handle );
		}
		catch( ... )
		{
			return false;
		}
		SwitchToSubObject( sub_handle );
		ThreadId = thread_id;
		return true;
	};
	void Destroy() 
	{
		SwitchToSubObject( NULL );
	}
	unsigned long Id() const 
	{
		if( GetSubObject() == NULL )
			return 0;
		return ThreadId;
	}
	operator HANDLE() const
	{
		if( GetSubObject() == NULL )
			return INVALID_HANDLE_VALUE;
		return GetSubObject()->Handle();
	}
	bool Terminate( DWORD dwExitCode )
	{
		if( GetSubObject() == NULL )
			return false;
		return TerminateThread( GetSubObject()->Handle(), dwExitCode ) != FALSE;
	}
	DWORD Resume()
	{
		if( GetSubObject() == NULL )
			return ( DWORD )-1;
		return ResumeThread( GetSubObject()->Handle() );
	}
	DWORD Suspend()
	{
		if( GetSubObject() == NULL )
			return ( DWORD )-1;
		return SuspendThread( GetSubObject()->Handle() );
	}
	bool GetExitCode( LPDWORD lpExitCode )
	{
		if( GetSubObject() == NULL )
			return false;
		return GetExitCodeThread( GetSubObject()->Handle(), lpExitCode ) != FALSE;
	}
};

#endif
